<template>
  <div class="login-container">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      auto-complete="on"
      label-position="left"
    >

      <div class="title-container">
        <h3 class="title">登录</h3>
      </div>

      <el-form-item prop="account">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          ref="username"
          v-model="loginForm.account"
          placeholder="Username"
          name="username"
          type="text"
          tabindex="1"
          auto-complete="on"
        />
      </el-form-item>

      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input
          :key="passwordType"
          ref="password"
          v-model="loginForm.password"
          :type="passwordType"
          placeholder="Password"
          name="password"
          tabindex="2"
          auto-complete="on"
          @keyup.enter.native="handleLogin"
        />
        <span class="show-pwd" @click="showPwd">
          <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
        </span>
      </el-form-item>

      <el-button
        :loading="loading"
        type="primary"
        style="width:100%;margin-bottom:30px;"
        @click.native.prevent="handleLogin"
      >登录</el-button>
      <div style="width:100%;display: flex;flex-direction: row;justify-content: space-around;">
        <div>
          <el-button @click="dialogVisible2 = true">忘记密码</el-button>
          <el-dialog title="忘记密码" :visible.sync="dialogVisible2" width="50%" :before-close="handleClose">
            <input id="phone" v-model="phone" type="text" required class="search-container" placeholder="输入绑定的手机号">
            <input id="account" v-model="account" type="text" class="search-container" placeholder="输入自己的学生号">
            <span slot="footer" style="display: flex;justify-content: center;">
              <el-button @click="dialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="forgot">申请</el-button>
            </span>
          </el-dialog>
        </div>
        <div>
          <el-button @click="dialogVisible = true">注册</el-button>
          <el-dialog title="注册" :visible.sync="dialogVisible" width="50%" :before-close="handleClose">
            <input id="account" v-model="account" type="text" class="search-container" required placeholder="输入你的学号">
            <input id="phone" v-model="phone" type="phone" class="search-container" required placeholder="输入你的电话">
            <input
              id="password"
              v-model="password"
              type="password"
              class="search-container"
              required
              placeholder="设置你的密码"
            >
            <input
              id="confirmPassword"
              v-model="confirmPassword"
              class="search-container"
              type="password"
              required
              placeholder="确认你的密码"
            >
            <span slot="footer" style="display: flex;justify-content: center;">
              <el-button @click="dialogVisible = false">取 消</el-button>
              <el-button type="submit" @click="Enroll">注册</el-button>
            </span>
          </el-dialog>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script>
import { validUsername } from '@/utils/validate'
import { testApi } from '@/api/email'
import { Forgot } from '@/api/user'
import { Enroll } from '@/api/user'

export default {
  name: 'Login',
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!value) {
        callback(new Error('输入正确的格式'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('密码数位太少'))
      } else {
        callback()
      }
    }
    return {
      account: '',
      username: '',
      password: '',
      confirmPassword: '',
      phone: '',
      input1: '',
      input2: '',
      dialogVisible: false,
      dialogVisible2: false,
      loginForm: {
        account: '1',
        password: '1'
      },
      loginRules: {
        account: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }]
      },
      loading: false,
      passwordType: 'password',
      redirect: undefined
    }
  },
  computed: {
    isEqual() {
      return this.input1 === this.input2
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  created() {
    // this.test()
  },
  methods: {
    async login() {
      console.log('Request:', this.user)
      try {
        const response = await this.$axios.post('/api/login', {
          username: this.username,
          password: this.password
        })

        if (response.data.success) {
          // 登录成功，存储账号信息
          this.account = response.data.account
          // 可以在这里执行其他登录成功的操作，如跳转到主页
        } else {
          alert(response.data.message)
        }
      } catch (error) {
        // 处理错误情况
        console.error('Login error:', error)
        alert('An error occurred during login.')
      }
    },
    async forgot() {
      console.log('Request:', this.user)
      const data = {
        account: this.account,
        phone: this.phone
      }
      try {
        const response = await Forgot(data)
        console.log(response)
        // 处理响应
        console.log(response.data)
      } catch (error) {
        // 处理错误
        console.error('Error:', error)
      }
    },
    async Enroll() {
      console.log('Request:', this.user)
      const data = {
        account: this.account,
        phone: this.phone,
        password: this.password
      }
      try {
        const response = await Enroll(data)
        console.log(response)
        // 处理响应
        console.log(response.data)
      } catch (error) {
        // 处理错误
        console.error('Error:', error)
      }
    },

    async submitForm() {
      // 发送数据到服务器端的API
      try {
        const response = await this.$http.post('/api/data', { data: this.inputData })
        // 处理响应
      } catch (error) {
        // 处理错误
      }
    },
    handleClose(done) {
      // 可以在这里处理关闭弹窗前的逻辑，比如表单验证
      done()
    },
    async test() {
      try {
        const res = await testApi()
        console.log(res)
      } catch (error) {
        console.log(error)
      }
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true // actions
          this.$store.dispatch('user/login', this.loginForm).then((res) => {
            console.log(res)
            this.$router.push({ path: this.redirect || '/' })
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

.search-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  border: 1px solid #141313;
  /* 边框颜色 */
  border-radius: 4px;
  /* 圆角 */
  overflow: hidden;
  /* 防止边框线条不连贯 */
  width: 240px;
  margin: auto;
  height: 40px;
  margin-top: 40px;
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
  background-repeat: no-repeat;
  background-size: 100% 100%;
  position: fixed;
  height: 100%;
  width: 100%;
  overflow: hidden;

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: black;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
</style>
